package com.hmkj.web.controller.simulation;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.PriceHelper;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.simulation.SubscribeModel;
import com.hmkj.core.po.account.AccountSimulation;
import com.hmkj.core.po.simulation.OrderSimulation;
import com.hmkj.core.po.simulation.Subscribe;
import com.hmkj.core.po.simulation.UserSubscribe;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.account.AccountSimulationService;
import com.hmkj.core.service.simulation.OrderSimulationService;
import com.hmkj.core.service.simulation.SubscribeService;
import com.hmkj.core.service.simulation.UserSubscribeService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * ......................我佛慈悲......................
 * ......................_oo0oo_.......................
 * .....................o8888888o......................
 * .....................88" . "88......................
 * .....................(| -_- |)......................
 * .....................0\  =  /0......................
 * ...................___/`---'\___....................
 * ..................' \\|     |// '...................
 * ................/ \\|||  :  |||// \.................
 * .............../ _||||| -卍-|||||- \................
 * ..............|   | \\\  -  /// |   |...............
 * ..............| \_|  ''\---/''  |_/ |...............
 * ..............\  .-\__  '-'  ___/-. /...............
 * ............___'. .'  /--.--\  `. .'___.............
 * .........."" '<  `.___\_<|>_/___.' >' ""............
 * ........| | :  `- \`.;`\ _ /`;.`/ - ` : | |.........
 * ........\  \ `_.   \_ __\ /__ _/   .-` /  /.........
 * ....=====`-.____`.___ \_____/___.-`___.-'=====......
 * ......................`=---='.......................
 * ....................................................
 * .................佛祖开光 ,永无BUG...................
 */
@Api(description = "模拟Json")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/simulation/index")
public class AppSimulationIndexController extends GenericController<Integer, AccountSimulation> {

    @Resource
    private OrderSimulationService orderSimulationService;
    @Resource
    private SubscribeService subscribeService;
    @Resource
    private UserSubscribeService userSubscribeService;
    @Resource
    private AccountSimulationService accountSimulationService;
    @Resource
    private UserService userService;


    @ApiOperation(value = "最什么", notes = "最什么")
    @ResponseBody
    @RequestMapping(value = "/most", method = RequestMethod.POST)
    public ResultEntity most(@ApiParam("类型:1 最赚钱，2 最稳健，3最人气 ") @RequestParam(required = true) Integer type) throws Exception {
        User user = getLoginUser();
        List<Subscribe> list = new ArrayList<>();
        if (StringUtils.isBlank(type.toString())) {
            throw new BussinessException("参数有误");
        }
        String type1 ="";
        if (1 == type){
            type1 = "mostEarn";
        } else if (2 == type){
            type1 ="mostSteady";
        }else if (3 == type){
            type1 ="mostPopular";
        }
        if (type1.equals("mostEarn")) { //最赚钱
            list = subscribeService.select(new Subscribe(t -> {
                t.setMostEarn(Subscribe.MOSTEARN.T2.code);
            }));
        } else if (type1.equals("mostSteady")) { //最稳健
            list = subscribeService.select(new Subscribe(t -> {
                t.setMostSteady(Subscribe.MOSTSTEADY.T2.code);
            }));
        } else if (type1.equals("mostPopular")) { //最人气
            list = subscribeService.select(new Subscribe(t -> {
                t.setMostPopular(Subscribe.MOSTPOPULAR.T2.code);
            }));
        } else {
            throw new BussinessException("参数有误");
        }

        List<SubscribeModel> modelList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Subscribe subscribe : list) {
                User user1 = userService.selectByPrimaryKey(subscribe.getUserId());
                SubscribeModel model = new SubscribeModel();
                BeanUtils.copyProperties(subscribe, model);
                //30天收益率
                Map param = new HashMap<>();
                param.put("userId", subscribe.getUserId());
                param.put("date", 30);
                param.put("status", OrderSimulation.STATUS.T7.code);
                BigDecimal totalBuy = BigDecimal.ZERO;
                BigDecimal totalWin = BigDecimal.ZERO;
                List<OrderSimulation> wins = orderSimulationService.selectOrderSimulateForTime(param);
                if (CollectionUtils.isNotEmpty(wins)) {
                    for (OrderSimulation order : wins) {
                        totalBuy = totalBuy.add(order.getTradeCredit());
                        totalWin = totalWin.add(order.getProfitCount());
                    }
                    model.setEarnings(PriceHelper.format(totalWin.divide(totalBuy.multiply(BigDecimal.valueOf(10000)), 4, RoundingMode.CEILING), 4));
                } else {
                    model.setEarnings(BigDecimal.valueOf(0));
                }

                //盈利策略数量
                List<OrderSimulation> win = orderSimulationService.selectProfitOrderSimulateForTime(param);
                if (CollectionUtils.isNotEmpty(win)) {
                    model.setWinRate(PriceHelper.format(BigDecimal.valueOf(win.size()).divide(BigDecimal.valueOf(orderSimulationService.selectCount(new OrderSimulation(t -> {
                        t.setUserId(subscribe.getUserId());
                        t.setStatus(OrderSimulation.STATUS.T7.code);
                    }))), 4, RoundingMode.CEILING), 4));
                } else {
                    model.setWinRate(BigDecimal.ZERO);
                }
                if (StringUtils.isNotBlank(user1.getAvatarUrl())) {
                    model.setAvatarUrl(user1.getAvatarUrl());
                }

                //总人气
                List<UserSubscribe> listPopular = userSubscribeService.select(new UserSubscribe(t -> {
                    t.setSubscriberId(subscribe.getId());
                    t.setIsSub(UserSubscribe.ISSUB.T2.code);
                }));

                if (CollectionUtils.isNotEmpty(listPopular)) {
                    model.setPopular(BigDecimal.valueOf(listPopular.size()));
                } else {
                    model.setPopular(BigDecimal.ZERO);
                }
                //查询是否关注
                if (user != null) {
                    //查询是否关注
                    UserSubscribe userSubscribe = userSubscribeService.selectOne(new UserSubscribe(t -> {
                        t.setUserid(user.getId());
                        t.setIsSub(UserSubscribe.ISSUB.T2.code);
                        t.setSubscriberId(subscribe.getId());
                    }));
                    model.setIsSub(null != userSubscribe ? 1 : 0);
                } else {
                    model.setIsSub(0);
                }
                modelList.add(model);
            }
            Collections.sort(modelList, (o1, o2) -> o2.getEarnings().compareTo(o1.getEarnings()));
        }
        return ok(modelList);
    }


    @ApiOperation(value = "高手排行", notes = "高手排行")
    @ResponseBody
    @RequestMapping(value = "/rank", method = RequestMethod.POST)
    public ResultEntity rank(@ApiParam("类型  1：总收益 2：日收益 3：周收益 4：月收益") @RequestParam(required = true) String type) throws Exception {
        User user = getLoginUser();
        Map<String, Object> data = new HashMap<>();
        if (StringUtils.isBlank(type) || (!type.equals("1") && !type.equals("2") && !type.equals("3") && !type.equals("4"))) {
            throw new BussinessException("参数有误");
        }
        List<Subscribe> list = subscribeService.select(new Subscribe(t -> {
            t.setDelFlag(Subscribe.DELFLAG.NORMAL.code);
        }));

        List<SubscribeModel> modelList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Subscribe subscribe : list) {
                User user1 = userService.selectByPrimaryKey(subscribe.getUserId());
                SubscribeModel model = new SubscribeModel();
                BeanUtils.copyProperties(subscribe, model);
                //收益率
                Map param = new HashMap<>();
                param.put("userId", subscribe.getUserId());
                param.put("status", OrderSimulation.STATUS.T7.code);
                if (type.equals("2")) {
                    param.put("date", 1);
                } else if (type.equals("3")) {
                    param.put("date", 7);
                } else if (type.equals("4")) {
                    param.put("date", 30);
                } else {
                    param.put("date", null);
                }
                BigDecimal totalBuy = BigDecimal.ZERO;
                BigDecimal totalWin = BigDecimal.ZERO;
                List<OrderSimulation> wins = orderSimulationService.selectOrderSimulateForTime(param);
                if (CollectionUtils.isNotEmpty(wins)) {
                    for (OrderSimulation order : wins) {
                        totalBuy = totalBuy.add(order.getTradeCredit());
                        totalWin = totalWin.add(order.getProfitCount());
                    }
                    model.setEarnings(PriceHelper.format(totalWin.divide(totalBuy.multiply(BigDecimal.valueOf(10000)), 4, RoundingMode.CEILING), 4));
                } else {
                    model.setEarnings(BigDecimal.valueOf(0));
                }

                //盈利策略数量
                List<OrderSimulation> win = orderSimulationService.selectProfitOrderSimulateForTime(param);
                if (CollectionUtils.isNotEmpty(win)) {
                    model.setWinRate(PriceHelper.format(BigDecimal.valueOf(win.size()).divide(BigDecimal.valueOf(orderSimulationService.selectCount(new OrderSimulation(t -> {
                        t.setUserId(subscribe.getUserId());
                        t.setStatus(OrderSimulation.STATUS.T7.code);
                    }))), 4, RoundingMode.CEILING), 4));
                } else {
                    model.setWinRate(BigDecimal.ZERO);
                }
                if (StringUtils.isNotBlank(user1.getAvatarUrl())) {
                    model.setAvatarUrl(user1.getAvatarUrl());
                }
                    model.setUserName(user1.getUserName());
                //总人气
                List<UserSubscribe> listPopular = userSubscribeService.select(new UserSubscribe(t -> {
                    t.setSubscriberId(subscribe.getId());
                    t.setIsSub(UserSubscribe.ISSUB.T2.code);
                }));

                if (CollectionUtils.isNotEmpty(listPopular)) {
                    model.setPopular(BigDecimal.valueOf(listPopular.size()));
                } else {
                    model.setPopular(BigDecimal.ZERO);
                }
                modelList.add(model);
            }
            Collections.sort(modelList, (o1, o2) -> o2.getEarnings().compareTo(o1.getEarnings()));
        }
        if (CollectionUtils.isNotEmpty(modelList)) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getUserId() == user.getId()) {
                    data.put("rank", i + 1);
                    break;
                } else {
                    data.put("rank", "--");
                }
            }
        } else {
            data.put("rank", "--");
        }
        //data.put("name", user.getUserName());
       // data.put("photo", StringUtils.isBlank(user.getAvatarUrl()) ? "" : user.getAvatarUrl());
        AccountSimulation accountSimulation = accountSimulationService.selectOne(new AccountSimulation(t->{
            t.setUserId(user.getId());
        }));
        if (PriceHelper.isGreaterThan(accountSimulation.getAvailable(), BigDecimal.valueOf(10000))){
            data.put("money", PriceHelper.format(accountSimulation.getAvailable().multiply(new BigDecimal("0.0001"))) + "万元");
        }else {
            data.put("money", PriceHelper.format(accountSimulation.getAvailable()) + "元");
        }
        Subscribe subscribe = subscribeService.selectOne(new Subscribe(t->{
            t.setUserId(user.getId());
        }));
        data.put("id", subscribe.getId());
        //data.put("list", list);
        data.put("modelList",modelList);
        return ok(data);
    }

}
